import classNames from 'classnames';
import React, { useState, useEffect, memo } from 'react';
import _ from 'lodash';
import './index.less';

const TjSlideSelect: React.FC<ITjSlideSelectProps> = memo((props) => {
  const [value, setValue] = useState<IValueType | undefined>(props.defaultValue);

  const onChange = (v: IValueType) => {
    if (props.disabled) {
      return;
    }
    if (v === props.value) {
      return;
    }
    if (props.onChange) {
      props.onChange(v);
    } else {
      setValue(v);
    }
  };

  useEffect(() => {
    if (props.value || _.isBoolean(props.value) || props.value === 0) {
      setValue(props.value);
    }
  }, [props.value]);

  return (
    <div className="tj-slide-select">
      <div className="list">
        {props.items.map((v, i) => {
          return (
            <div
              key={i}
              className={classNames('item', { 'item-active': value === v.value })}
              onClick={() => onChange(v.value)}
            >
              {v.label}
            </div>
          );
        })}
      </div>
    </div>
  );
});

export type ITjSlideSelectItemsType = {
  label: string;
  value: IValueType;
};

export type IValueType = string | number | boolean;

export interface ITjSlideSelectProps {
  items: ITjSlideSelectItemsType[];
  onChange?: (value: IValueType) => void;
  value?: IValueType;
  defaultValue?: IValueType;
  disabled?: boolean;
}

export { TjSlideSelect };
